package com.asset.dispoal.role.service.commom;

import com.asset.dispoal.role.domain.db.entity.GbRoleDo;
import com.asset.dispoal.role.domain.db.mapper.GbRoleMapper;
import com.asset.dispoal.role.dto.GbRoleRequest;
import com.asset.dispoal.role.service.converter.RoleConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.GlobalHeader;
import tech.mhuang.pacebox.springboot.protocol.Result;

/**
 * @author qr
 * @date 2022/3/1$
 */
@Component
public class InsertRoleCommand implements BaseCommand<GbRoleRequest, Result> {

    @Autowired
    private GbRoleMapper gbRoleMapper;

    @Autowired
    BaseIdeable<String> snowFlake;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result execute(GbRoleRequest request) {
        if (request == null) {
            throw new BusinessException("参数错误");
        }
        request.setId(snowFlake.generateId());
        GlobalHeader loginUser = GlobalHeaderThreadLocal.getOrException();
        GbRoleDo roleDO = RoleConverter.INSTANCE.reqToDo(request);
        roleDO.setCompanyId(loginUser.getCompanyId());
        roleDO.setCreateUserId(loginUser.getUserId());
        gbRoleMapper.insert(roleDO);
        if (CollectionUtil.isNotEmpty(request.getUserIds())) {
            gbRoleMapper.insertAuthUser(roleDO.getId(), request.getUserIds());
        }
        if (CollectionUtil.isNotEmpty(request.getDepartIds())) {
            gbRoleMapper.insertAuthDepart(roleDO.getId(), request.getDepartIds());
        }
        return Result.ok();
    }
}
